#! /usr/bin/env python

import sys
import getopt
import os
import uuid
import cgi
from datetime import date
import tempfile
import tarfile

from ivic.core import Config, project_path, Utils

__config_file = project_path('/etc/ivic/vstore.yaml')

def usage():
    print """Usage: ivic-vstore <command> [ARGS] [OPTIONS]

Available commands are:
    
    create      Create a virtual machine template
    publish     Publish a virtual machine template to iVIC Portal
    list        List available virtual machine templates

More...

    ivic-vstore create [options]

        --Name          Name of virtual machine template
        --Description   Describe virtual machine template
        --Distribution  Specify linux distribution, supported distributions are debian, ubuntu, fedora and centos
        --Release       Specify release of specific distribution.
                            Debian: etch, lenny
                            Ubuntu: gutsy, hardy, intrepid
                            Fedora: fedora-core-7, fedora-core-8, fedora-core-9
                            CentOS: centos-4, centos-5

    ivic-vstore publish [--cert path_to_cert_file] [--ca_cert path_to_ca_cert_file] <uuid | xml_file_name | xml_file_path>

    ivic-vstore destroy <uuid | xml_file_name | xml_file_path>

    ivic-vstore list
    
    ivic-vstore convert -f rootfs -t nfsmount UUID
   
    ivic-vstore modify <cmd> [params] <uuid | xml_file_name | xml_file_path>

        Available cmds are:

            shell
            capability <add | delete> <capability_name>
            package <add | delete> <package_name>

    """
#******************************************************************************************************#
#add by jch for converting tar.gz to image
def extractRootfs(tar_file_name,output_path):
    """  extract rootfs's tar.gz file   """
    try:
        tar = tarfile.open(tar_file_name)
        tar.extractall(path=output_path)
        tar.close()
        return output_path;
    except Exception,err:
        error("extract the tar.gz file:"%str(err))
        return None;


#******************************************************************************************************#

def create(argv):
    """
    Create a virtual machine template
    """

    # default arguments
    args = {
        'Name': 'vMachine-' + date.today().strftime('%Y%m%d'), 
        'Description': 'iVIC basic virtual machine template', 
        'Distribution': 'debian',
        'Release': 'lenny',
        'Kernel': '2.6.26-1-686',
        'Repository': 'http://mirror.ivic.org.cn/debian', 
        'Method': 'rootfs',
        'URL': 'http://frenzy.ivic.org.cn/vstore/rootfs/uuid.tar.gz',
        'COWDir':'',
        'Packages': 'base-files',
#        'Mem': 256,
#        'DiskSize': 1,
        'PreferedSettings': '<PreferedSettings><Mem>256</Mem><DiskSize>1G</DiskSize></PreferedSettings>',
        'UUID': str(uuid.uuid1()),
        'Capabilities': 'vNode',
   }

    try:
        # Get command line options for create
        options = args.keys()
        count = 0
        while count < len(options):
            options[count] = options[count] + '='
            count = count + 1

        # Update args by command line
        if len(argv) > 0:
            opts, files = getopt.getopt(argv, 'none', options)
            for opt, arg in opts:
                opt = opt[2:]
                args[opt] = arg

        # Get external address instead of local host name
        external_address = __config['external_address']
        if not external_address:
            external_address = Utils.external_address()

        # Get listen_port
        listen_port = __config['listen_port']

        # update URL
        args['URL'] = 'http://%s:%d/%s/%s.tar.gz' % (external_address, listen_port, __config['rootfs_vpath'], args['UUID'])
        
        # Get & update repository
        dist = args['Distribution']
        release = args['Release']
        if not __config['repos']['dists'].has_key(dist) :
            error('Distribution %s not supported.' % dist)
        elif not __config['repos']['dists'][dist]['releases'].has_key(release):
            error('Release %s of %s not supported.' % (release, dist))
        else:
            args['Repository'] = __config['repos']['dists'][dist]['releases'][release]['repository']

        # Create specific VMT
        if do_create(args):
            export_xml(args)
        else:
            error('Create operation failed.')

        # Remove temperary files
        os.system('rm -rf %s' % __config['rootfs_path'] + '/' + args['UUID'])

    except getopt.GetoptError, err:
        error(str(err))

    pass

def list(argv):
    """
    List current virtual machine templates
    """
    xmls = run('ls %s | grep -w xml$' % __config['template_path']).split()
    for xml in xmls:
        vmt = import_xml(__config['template_path'] + '/' + xml)
        print xml
        for key in vmt.keys():
            print '\t', key, '=', vmt[key]
def convert(argv):
    """
    """
    try:
        opts, uuids = getopt.getopt(argv, "f:t:w:")
        flags = False;
        rootfs=""
        nfsmount=""
        window_img = ""
        for opt, arg in opts:
            if opt == '-f':
                rootfs = arg
            if opt == '-t':
                nfsmount = arg
            if opt == '-w':
                flags = True;
                window_img = arg;
        print flags;
        print window_img;
        
        # Extract uuid
        if len(uuids) == 0 :
            error('Invalid arguments for convert.')
        old_uuid = uuids[0]
        args = import_xml(__config['template_path'] + '/' +old_uuid+".xml")
        if rootfs == "":
            rootfs = __config["rootfs_path"]
        if nfsmount == "":
            nfsmount = __config["nfsbase_path"]
        distribution = args['Distribution'].strip()
        diskSize = 1 #args['DiskSize'].strip()
        # update uuid
        args["UUID"] = str(uuid.uuid1())
        args["Method"] = "nfsmount"
        if flags==False:
            extract_rootfs_output_path = tempfile.mkdtemp()
            rootfs_file_name = rootfs+"/"+old_uuid+".tar.gz"
            print rootfs_file_name
            extract_rootfs_output_path = extractRootfs(rootfs_file_name,extract_rootfs_output_path)
            new_uuid = args["UUID"]
            vmImagePath = nfsmount+"/"+new_uuid
            convert_command = __config['script_path'] + '/' + "create_kvm_image.sh "+extract_rootfs_output_path+" "+vmImagePath + " "+str(diskSize)+" "+distribution+" "+new_uuid
            os.system(convert_command)
            os.system("rm -R " + extract_rootfs_output_path)
        else:
            vmImagePath = nfsmount+"/"+args["UUID"]
            os.system("cp "+window_img+" "+vmImagePath+".img")
        
        # Get external address instead of local host name
        external_address = __config['external_address']
        if not external_address:
            external_address = Utils.external_address()

        # update URL
        args['URL'] = 'nfs://%s%s/%s.img' % (external_address,  __config['nfsbase_path'], args['UUID'])
        # update cow dir
        args["COWDir"] = 'nfs://%s%s'%(external_address, __config['nfscow_path'])
        export_xml(args)
   
    except Exception,err:
        print "cann't convert :",str(err)

def publish(argv):
    """
    Publish a virtual machine template to iVIC Portal
    """

    args = {
        'uuid'          : 'undefined',
        'name'          : 'undefined',
        'os_type'       : 'undefined',
        'distribution'  : 'undefined',
        'kernel'        : 'undefined',
        'capabilities'  : 'undefined',
        'repository'    : 'undefined',
        'deploy_method' : 'undefined',
        'deploy_url'    : 'undefined',
        'prefer_settings'   : 'undefined',
        'node_type'     : 'undefined',
        'url'           : 'undefined',
        'description'   : 'undefined',
    }

    cert = ''
    ca_cert = ''

    try:
        # from command lines get cert info
        options = ['cert=', 'ca_cert=']
        opts, files = getopt.getopt(argv, 'none', options)

        for opt, arg in opts:
            if opt == '--cert':
                cert = arg
            if opt == '--ca_cert':
                ca_cert = arg

        # Extract xml path
        if len(files) == 0:
            error('Invalid arguments for publish.')
        path = get_path_from_param(files[0])

        # Import vmt info
        vmt = import_xml(path)
        args['uuid'] = path[-40:-4]
        args['name'] = vmt['Name']
        args['os_type'] = vmt['Distribution']
        args['distribution'] = vmt['Release']
        args['kernel'] = vmt['Kernel']
        args['capabilities'] = vmt['Capabilities']
        args['repository'] = vmt['Repository']
        args['deploy_method'] = vmt['Method']
        args['deploy_url'] = vmt['URL']
        args['deploy_cowdir'] = vmt['COWDir']
        args['prefer_settings'] = cgi.escape(vmt['PreferedSettings'])
        if vmt['Method'] == 'rootfs':
        	args['url'] = vmt['URL'][:vmt['URL'].rindex('rootfs')] + 'template/' + args['uuid'] + '.xml'
        else:
                # Get external address instead of local host name
                external_address = __config['external_address']
                if not external_address:
                    external_address = Utils.external_address()

                # Get listen_port
                listen_port = __config['listen_port']

                # update URL
                args['url'] = 'http://%s:%d/%s/%s.xml' % (external_address, listen_port, __config['template_vpath'], args['uuid'])
        #end if
        args['description'] = vmt['Description']

        rest_request = '';
        for x in args.keys():
            rest_request = rest_request + '<%s>%s</%s>' % (x, args[x], x)

        rest_request = '<VirtualMachineTemplate>%s</VirtualMachineTemplate>' % rest_request

        # Get Cert
        if not cert:
            try:
                cert = __config['client_key']
            except:
                cert = ''

        if not cert:
            error('Unable to find certificate.')

        # Get CA Cert
        if not ca_cert:
            try:
                ca_cert = __config['server_cert']
            except:
                ca_cert = ''

        if not ca_cert:
            error('Unable to find CA certificate to authenticate the server.')

        # Get REST endpoint
        try:
            rest_endpoint = __config['server_url']
        except:
            rest_endpoint = ''

        if not rest_endpoint:
            error('Invalid rest endpoint.')

        header_file = run('mktemp')

        curl_args = '-X POST -H "Content-Type: text/xml" -H "Accept: text/xml" --cert %s --cacert %s -d "%s" --dump-header %s %s' \
                    % (cert, ca_cert, rest_request, header_file, rest_endpoint)
        print 'curl %s 1>/dev/null 2>/dev/null' % curl_args
        result = os.system('curl %s 1>/dev/null 2>/dev/null' % curl_args)
        if result != 0:
            error('curl error.')

        try:
            fd = open(header_file)
            result = fd.readline() 
        except: 
            fd.close()
            error('curl error.')
        fd.close()

        result = result.strip()
        print result[result.find(' ') + 1:]

    except Exception, err:
        error('Unable to publish virtual machine template: %s' % str(err))

def destroy(argv):
    """
    Destroy a virtual machine template
    """
    # from command lines get cert info

    # Extract xml path
    if len(argv) == 0:
        error('Invalid arguments.')
    path = get_path_from_param(argv[0])
    uuid = path[-40:-4]
    rootfs = __config['rootfs_path'] + '/' + uuid + ".tar.gz"
    template = __config['template_path'] + '/' + uuid + ".xml"

    # Perform deletion
    os.system('rm -rf %s' % rootfs)
    os.system('rm -rf %s' % template)

    print 'Virtual machine template %s has beed destroyed.' % uuid

def info(argv):
    """
    Show virtual machien template information
    """
    if len(argv) == 0:
        error('Invalid arguments.')

    path = get_path_from_param(argv[0])
    uuid = path[-40:-4]
    vmt = import_xml(path)
    print uuid
    for key in vmt.keys():
        print '\t', key, '=', vmt[key]

def modify(argv):
    """
    Modify virtual machine template
    vstore modify <uuid|filename|filepath> <shell | capability <add | delete> CAP[ CAP CAP ...] | package install PKG[ PKG PKG ...]>
    """

    if len(argv) < 2:
        error('Invalid arguments')

    path = get_path_from_param(argv[0])
    command = argv[1]

    ops = {
        'shell': do_modify_shell,
        'capability': do_modify_capability,
        'package': do_modify_package,
    }

    if command in ops.keys():
        ops[command](path, argv[2:])
    else:
        error('Invalid arguments.')

def error(msg):
    """
    Display an error message and exit.
    """
    # print msg
    # sys.exit()
    raise Exception, msg

def init_create_dirs():
    """
    Create repos dirs if necessary
    """
    if not os.path.exists(__config['rootfs_path']):
        os.system('mkdir -p ' + __config['rootfs_path'])

    if not os.path.exists(__config['template_path']):
        os.system('mkdir -p ' + __config['template_path'])

def do_main(argv):
    """
    vstore Main
    """
    # Load global configurations 
    try:
        global __config
        __config= Config.load(__config_file)
    except:
        error('Unable to load config file.')

    from ivic.core import Logging
    logger = Logging.get_logger(__name__, filename = __config["vstore_log"], default = True)
    logger.info('args: %s' % repr(argv))

    # Create repos dir if necessary.
    init_create_dirs()
    
    # Parse command lines and dispatch requests
    command = argv[0]
    if command == 'create':
        create(argv[1:])
    elif command == 'list':
        list(argv[1:])
    elif command == 'publish':
        publish(argv[1:])
    elif command == 'help':
        usage()
    elif command == 'destroy':
        destroy(argv[1:])
    elif command == 'info':
        info(argv[1:])
    elif command == 'modify':
        modify(argv[1:])
    elif command == 'convert':
        convert(argv[1:])
    else:
        error('Unsupported command: ' + command)

def get_path_from_param(path):
    """
    Return full path to the template xml file representing p, 
    p can be a UUID, xml file name, or full path
    """
    # if path is pure xml name
    if not os.path.exists(path):
        path = __config['template_path'] + '/' + path
    # if path is uuid
    if not os.path.exists(path):
        path = path + '.xml'
    if not os.path.exists(path):
        error('Unable to find virtual machine template.')
    return path


def do_create(args):
    """
    Create VMT specified by args.
    Return true if successful, false if not.
    """
    template_xml = __config['template_path'] + '/' + args['UUID'] + '.xml'
    rootfs_dir = __config['rootfs_path'] + '/' + args['UUID']

    try:

       # Exit if specific uuid exists.
        if os.path.exists(template_xml):
            error('Virtual machine template with UUID %s already exist.' % args['UUID'])
    
        # Download root fs using debootstrap or rinse
        # if args['Distribution'] == 'debian':
        if __config['repos']['dists'][args['Distribution']]['install'] == 'debootstrap':
            # Use debian mirrror
            arg_debootstrap = '--arch=i386 --include=%s %s %s %s' % (args['Packages'], args['Release'], rootfs_dir, args['Repository'])

            # Download root fs
            if os.system('debootstrap %s' % arg_debootstrap) != 0:
                error('Creating debian based virtual machine failed.')

        # elif args['Distribution'] == 'fedora' or args['Distribution'] == 'centos':
        elif __config['repos']['dists'][args['Distribution']]['install'] == 'rinse':
            # Use centos or fedora mirror
            arg_rinse = '--distribution %s --directory %s' % (args['Release'], rootfs_dir)
            mirror = '[%s]\nmirror = %s' % (args['Release'], args['Repository'])

            # Modify mirror info
            try:
                fsock = open('/etc/rinse/rinse.conf', 'w')
                try:
                    fsock.write(mirror)
                finally:
                    fsock.close()
            except IOError, err:
                error('Failed to set rinse mirror, %s' % str(err))
    
            # Download root fs
            if os.system('rinse %s' % arg_rinse) != 0:
                error('Creating rpm based virtual machine failed.')
        elif  __config['repos']['dists'][args['Distribution']]['install'] == 'windows':
            #add by jch for creating windows tar.gz
            disk_image =  __config['repos']['dists'][args['Distribution']]['releases'][args['Release']]['disk-image']
            os.system(__config['script_path'] + '/' + 'windows_extract.sh %s' % disk_image)
            basename = os.path.basename(disk_image)
            os.system('mv %s.tar.gz %s.tar.gz' % (basename,rootfs_dir))
            return True

        else:
            error('Unsupported distribution or release')

        print 'EXEC: Preparing post-install script.'

        # Run post-install script
        post_install_script = __config['repos']['dists'][args['Distribution']]['releases'][args['Release']]['post-install']
        if post_install_script:
            post_script = __config['script_path'] + '/' + post_install_script
            print 'EXEC: %s' % post_script

            os.system('cp %s %s/tmp' % (post_script, rootfs_dir))
            os.system('mount proc %s/proc -t proc' % rootfs_dir)
            os.system('chroot %s /tmp/%s' % (rootfs_dir, post_install_script))
            os.system('umount %s/proc' % rootfs_dir)

            print 'EXEC: Post-install script executed.'

        # Create tar ball
        os.system('tar czf %s -C %s .' % (rootfs_dir + '.tar.gz', rootfs_dir))
        
        return True

    except Exception, err:
        print str(err)
        return False

def do_modify_shell(path, argv):
    """
    Open a chroot shell on virtual machine template
    """
    uuid = path[-40:-4]
    rootfs_path = __config['rootfs_path'] + '/' + uuid
    rootfs_arch = rootfs_path + '.tar.gz'

    # Make uuid direcotry
    print 'Making directory %s' % rootfs_path
    os.system('mkdir -p %s' % rootfs_path)

    # Untar
    print 'Unpackaging target virtual machine template %s...' % uuid
    os.system('tar xzf %s -C %s' % (rootfs_arch, rootfs_path))    

    # Mount proc
    print 'Mounting proc fs...'
    os.system('mount proc %s/proc -t proc' % rootfs_path)

    # Chroot
    print 'Enterting virtual machine template...'
    os.system('chroot %s' % rootfs_path)

    # Unchroot
    print 'Leaving virtual machine template...'

    # Unmount 
    print 'Unmounting proc fs...'
    os.system('umount %s/proc' % rootfs_path)

    # Retar
    print 'Repacking virtual machine template...'
    os.system('mv %s %s-orig.tar.gz' % (rootfs_arch, rootfs_path))
    os.system('tar czf %s -C %s .' % (rootfs_arch, rootfs_path))
    
    # Clean
    print 'Removing temperary files...'
    os.system('rm -rf %s' % rootfs_path)

    # Prompt
    print 'Modification saved successfully. Original vmt has been saved to %s-orig.tar.gz' % uuid

def do_modify_capability(path, argv):
    """
    Add or remove capabilities
    """
    if len(argv) < 2:
        error('Invalid arguments.')

    # Load original confs
    vmt = import_xml(path)
    caps = vmt['Capabilities'].split(',')

    # Add or remove capabilities
    command = argv[0]
    if command == 'add':
        for cap in argv[1:]:
            caps.append(cap)
    elif command == 'delete':
        for cap in argv[1:]:
            caps.remove(cap)
    else:
        error('Invalid arguments.')

    if len(caps) == 0:
        caps.append('vNode')
    # Remove duplicate ones
    from sets import Set
    vmt['Capabilities'] = str.join(',', Set(caps))

    # Export xml
    vmt['UUID'] = path[-40:-4]
    export_xml(vmt)

    # Prompt
    print 'Modification saved successfully.'

def do_modify_package(path, argv):
    """
    Install packages
    """
    print "Package installation is not supported in this version, you may use 'vstore modify shell' to logon to vmt and install packages manually."
    pass

def export_xml(args):
    """
    Save virtual machine template info to xml.
    """
    from xml.dom import minidom,Node
    doc = minidom.Document()
    vtemplate = doc.createElement("vTemplate") 
    vtemplate.setAttribute('uuid', args['UUID'])
    doc.appendChild(vtemplate)

    name = doc.createElement("Name")
    text = doc.createTextNode(args["Name"])
    name.appendChild(text)
    vtemplate.appendChild(name)

    description = doc.createElement('Description')
    text = doc.createTextNode(args['Description'])
    description.appendChild(text)
    vtemplate.appendChild(description)

 
    capabilities = doc.createElement("Capabilities")
    for caps in args['Capabilities'].split(','):
        capsNode = doc.createElement(caps)
        capabilities.appendChild(capsNode)
    
    vtemplate.appendChild(capabilities)

    os = doc.createElement("OS")
    type_node = doc.createElement("Type")
    text = doc.createTextNode('linux')
    type_node.appendChild(text)
    os.appendChild(type_node)

    distribution = doc.createElement("Distribution")
    text = doc.createTextNode(args["Distribution"])
    distribution.appendChild(text)
    release = doc.createElement("Release")
    text = doc.createTextNode(args["Release"])
    release.appendChild(text)
    kernel = doc.createElement("Kernel")
    text = doc.createTextNode(args["Kernel"])
    kernel.appendChild(text)
    packages = doc.createElement("Packages")
    text = doc.createTextNode(args["Packages"])
    packages.appendChild(text)
    os.appendChild(distribution)
    os.appendChild(release)
    os.appendChild(kernel)
    os.appendChild(packages)
    vtemplate.appendChild(os)

    repository = doc.createElement("Repository")
    text = doc.createTextNode(args["Repository"])
    repository.appendChild(text)
    vtemplate.appendChild(repository)
    
    deployinfo = doc.createElement("DeployInfo")
    method = doc.createElement("Method")
    text = doc.createTextNode(args["Method"])
    method.appendChild(text)
    url = doc.createElement("URL")
    text = doc.createTextNode(args["URL"])
    url.appendChild(text)
    
    cowdir = doc.createElement("COWDir")
    text = doc.createTextNode(args["COWDir"])
    cowdir.appendChild(text)
    
    
    #preferedsettings = doc.createElement("PreferedSettings")
    #mem = doc.createElement("Mem")
    #text = doc.createTextNode(str(args["Mem"])+"M")
    #mem.appendChild(text)
    #disksize = doc.createElement("DiskSize")
    #text = doc.createTextNode(str(args["DiskSize"])+"G")
    #disksize.appendChild(text)
    #preferedsettings.appendChild(mem)
    #preferedsettings.appendChild(disksize)

    """
    args['PreferedSettings'] is something like <PreferedSettings><name>value</name></PreferedSettings>
    """
    #ps = args['PreferedSettings'];
    #ps = ps[ps.find('<PreferedSettings>') + len('<PreferedSettings>'):ps.rfind('</PreferedSettings>')]

    #text = doc.createTextNode(ps)
    #preferedsettings.appendChild(text)
    #deployinfo.appendChild(preferedsettings)

    ps = minidom.parseString(args['PreferedSettings'])
    deployinfo.appendChild(ps.documentElement)

    deployinfo.appendChild(method)
    deployinfo.appendChild(url)
    deployinfo.appendChild(cowdir)
    vtemplate.appendChild(deployinfo)  
    
    __xmlfilepath = __config['template_path']
    import os #There is a node named os in the xml object above. So need to import again.
    if os.path.exists(__xmlfilepath):    
       pass
    else:
       os.mkdir(__xmlfilepath)
    
    try:
        fsock = open(__xmlfilepath + '/' + args['UUID'] + '.xml', 'w')
        try:
           fsock.write(doc.toprettyxml(indent=" "))
        finally:
           fsock.close()
    except IOError, err:
        print 'Unable to create xml document. %s' % str(err)

def import_xml(path):
    """
    Import VMT from xml
    """
    from xml.dom.minidom import parse
    try:
        doc = parse(path).documentElement
        result = {}

        # Get Name
        result['Name'] = doc.getElementsByTagName('Name')[0].firstChild.data.strip()

        # Get Destription
        result['Description'] = doc.getElementsByTagName('Description')[0].firstChild.data.strip()

        # Get Distribution
        result['Distribution'] = doc.getElementsByTagName('Distribution')[0].firstChild.data.strip()

        # Get Release
        result['Release'] = doc.getElementsByTagName('Release')[0].firstChild.data.strip()

        # Get Kernel
        result['Kernel'] = doc.getElementsByTagName('Kernel')[0].firstChild.data.strip()

        # Get Repository
        result['Repository'] = doc.getElementsByTagName('Repository')[0].firstChild.data.strip()

        # Get Deploy Method
        result['Method'] = doc.getElementsByTagName('Method')[0].firstChild.data.strip()

        # Get Deploy Url
        result['URL'] = doc.getElementsByTagName('URL')[0].firstChild.data.strip()
        result['COWDir'] = doc.getElementsByTagName('COWDir')[0].firstChild.data.strip()
        result['Packages'] = doc.getElementsByTagName('Packages')[0].firstChild.data.strip()

        # Get Capabilities
        def extract(x):
            if x.__class__.__name__ == 'Element':
                return x.tagName
        
        result['Capabilities'] = str.join(',', filter((lambda x: x), map(extract, doc.getElementsByTagName('Capabilities')[0].childNodes)))

        # Get PreferdSettings
        #from cgi import escape
        #result['PreferedSettings'] = escape(str.join('', doc.getElementsByTagName('PreferedSettings')[0].toxml().split()))
        result['PreferedSettings'] = str.join('', doc.getElementsByTagName('PreferedSettings')[0].toxml().split())

        return result
   
    except Exception, err:
        error('Unable to load xml %s, %s' % (path, str(err)))
        return None

def run(cmd):
    """
    Run a shell command and return stdout.
    """
    from subprocess import Popen, PIPE, STDOUT
    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
    output = p.stdout.read()
    return output.strip()

# add by liqin, invoked by /usr/bin/ivic-vstore script
# change old main to do_main
def main():
    if len(sys.argv) > 1:
        try:
        	do_main(sys.argv[1:])
        except Exception, msg:
            print str(msg)
    else:
        usage()
